import React, { Component } from 'react'
import { hashHistory } from 'react-router'
import { Carousel, Icon } from 'antd-mobile'
import TimerMixin from 'react-timer-mixin'
import reactMixin from 'react-mixin'
import { FooterTab } from '../footer'
import { Announcement } from '../public'
import { RegisterFormWrapper } from '../user'
import { myFetch, config } from '../utils'
import { OperatePosition } from './'

const { types } = config

const typeCodeArr = types.map(({TypeCode}) => TypeCode)

function translateTypeCode(code) {
  const filteredArr = types.filter(v => v.TypeCode === code)
  if (filteredArr[0]) {
    return filteredArr[0].TypeName
  }
  return ''
}

export default class MicroTrade extends Component {
  constructor() {
    super()
    this.fetchPriceList = this.fetchPriceList.bind(this)
    this.fetchGoodsList = this.fetchGoodsList.bind(this)
    this.state = {
      activeTabIndex: 0,
      chartTypeIndex: 4,
      goodsIndex: 0,
      priceList: [],
      goodsList: [],
      takePositionModal: false,
    }
  }
  componentDidMount() {
    this.fetchGoodsList()
    this.fetchPriceList()
    // timer
    this.setInterval(() => {
      this.fetchPriceList()
    }, 1000)
  }
  render() {
    const {
      activeTabIndex,
      chartTypeIndex,
      goodsIndex,
      priceList,
      goodsList,
      takePositionModal,
    } = this.state
    let current = {}
    if (priceList[activeTabIndex]) {
      current = priceList[activeTabIndex]
    }
    let selectedList = []
    if (current.TypeCode) {
      selectedList = goodsList.filter(v => v.TypeCode === current.TypeCode)
    }
    return (
      <div className={`rt-micro-trade-container`}>
        <img
          className={`rt-small-banner-img`}
          alt="small-banner"
          src={require('static/images/banner-s.png')}
          onClick={() => {
            hashHistory.push('/404')
          }}
        />

        <Announcement />

        <div className={`rt-goods-real-time-box`}>
          {
            priceList.map((v, i) => (
              <div
                key={v.TypeCode}
                className={`${activeTabIndex === i ? '-active' : ''}`}
                onClick={() => {
                  if (activeTabIndex === i) return
                  this.setState({
                    activeTabIndex: i,
                  })
                }}
              >
                <div className={`${v.UpDown === 1 ? '-go-up' : ''}`}>
                  <span className={`rt-name`}>{translateTypeCode(v.TypeCode)}</span>
                  <span className={`rt-price`}>{v.CurPrice}</span>
                  <Icon type={`${v.UpDown === 1 ? 'up' : 'down'}`} />
                </div>
              </div>
            ))
          }
        </div>

        <div className={`rt-statistics-price-box`}>
          <span>昨收：{current.Close}</span>
          <span>开盘：{current.Open}</span>
          <span>最高：{current.High}</span>
          <span>最低：{current.Low}</span>
        </div>

        <div className={`cm-scrollable-container`}>
          <div className={`rt-chart-genre-box`}>
            {
              ['分时线', '5分钟线', '30分钟线', '1小时线', '日线'].map((v, i) => (
                <span
                  key={i}
                  className={`${chartTypeIndex === i ? '-active' : ''}`}
                  onClick={() => {
                    if (chartTypeIndex === i) return
                    this.setState({
                      chartTypeIndex: i,
                    })
                  }}
                >
                  {v}
                </span>
              ))
            }
          </div>

          <img
            className={`rt-chart-img`}
            alt="chart"
            src={require('static/images/chart.png')}
          />

          <div className={`rt-about-user-account`}>
            <div className={`rt-left`}>
              <Icon type="user" />
              <span className={`rt-text`}>资产</span>
              <span className={`rt-balance`}>3,686.90元</span>
              <img
                alt="auth?"
                src={require('static/images/authed.png')}
              />
            </div>
            <div className={`rt-right`}>
              <Icon type="question" />
              <span className={`rt-adjust-sign`}>充值</span>
              <Icon type="question" />
              <span>提现</span>
            </div>
          </div>

          <div className={`rt-available-goods`}>
            {
              selectedList.map((v, i) => (
                <div
                  key={v.Code}
                  className={`rt-goods ${goodsIndex === i ? '-active' : ''}`}
                  onClick={() => {
                    this.fetchGoodsList()
                    if (goodsIndex === i) return
                    this.setState({
                      goodsIndex: i,
                    })
                  }}
                >
                  <span>{v.Weight}</span>
                  <span className={`rt-middle`}>{v.OpenChargeFee}元／手</span>
                  <span>波动盈亏{v.ProfitPerUnit}元</span>
                  {
                    goodsIndex === i
                    ? (
                      <div className={`cm-right-angle-trangle-box`}>
                        <div className={`cm-tick-box`}></div>
                      </div>
                    )
                    : null
                  }
                </div>
              ))
            }
          </div>

          <div className={`rt-button-group`}>
            <div
              className={`rt-up`}
              onClick={() => {
                this.setState({takePositionModal: true})
              }}
            >
              <Icon type="question" />
              <span>买涨</span>
            </div>
            <div className={`rt-down`}>
              <Icon type="question" />
              <span>买跌</span>
            </div>
          </div>

          <div className={`rt-order-title`}>
            正在交易的订单
          </div>

          <div className={`rt-order-box`}>
            {
              Array(3).fill(1).map(v => (
                <div key={Math.random()} className={`rt-order`}>
                  <div className={`rt-updown`}>
                    <span>涨</span>
                  </div>
                  <div className={`rt-profit-loss`}>
                    <img
                      alt="+-"
                      src={require('static/images/shield.png')}
                    />
                    <span>止盈损</span>
                  </div>
                  <div className={`rt-info`}>
                    <span className={`rt-name`}>3KG 工业银</span>
                    <span>开仓价 3433</span>
                  </div>
                  <div className={`rt-delta`}>
                    +24.00
                  </div>
                  <div className={`rt-op-btn`}>
                    <span>平仓</span>
                  </div>
                </div>
              ))
            }
            <div key={Math.random()} className={`rt-order -diff`}>
              <div className={`rt-updown`}>
                <span>涨</span>
              </div>
              <div className={`rt-profit-loss`}>
                <img
                  alt="+-"
                  src={require('static/images/active-shield.png')}
                />
                <span>止盈损</span>
              </div>
              <div className={`rt-info`}>
                <span className={`rt-name`}>3KG 工业银</span>
                <span>开仓价 3433</span>
              </div>
              <div className={`rt-delta`}>
                +24.00
              </div>
              <div className={`rt-op-btn`}>
                <span>平仓</span>
              </div>
            </div>
          </div>
        </div>
        <FooterTab
          defaultIndex={0}
        />
        <OperatePosition
          visible={takePositionModal}
          onClose={() => {
            this.setState({
              takePositionModal: false,
            })
          }}
        />
      </div>
    )
  }
  fetchPriceList() {
    myFetch(`/prices/realtime/getlist`)
      .then(rs => {
        if (rs && rs.PriceList && rs.PriceList.length > 0) {
          const filteredArr = rs.PriceList.filter(v => typeCodeArr.includes(v.TypeCode))
          if (filteredArr.length > 0) {
            this.setState({
              priceList: filteredArr,
            })
          }
        }
      })
  }
  fetchGoodsList() {
    myFetch(`/infos/goods/getlist`)
      .then(rs => {
        if (rs && rs.GoodsList && rs.GoodsList.length > 0) {
          const filteredArr = rs.GoodsList.filter(v => typeCodeArr.includes(v.TypeCode))
          if (filteredArr.length > 0) {
            this.setState({
              goodsList: filteredArr,
            })
          }
        }
      })
  }
}

reactMixin(MicroTrade.prototype, TimerMixin)